//
//  UploadViewController.m
//  Kfangchan
//
//  Created by liran on 14/11/25.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "UploadViewController.h"


#define HomeImagePath [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/Images/"]

@interface UploadViewController () {
    int tempTag;
    NSMutableDictionary *fileDic;
}

@property (strong, nonatomic) IBOutlet UIButton *idcardButton;
@property (strong, nonatomic) IBOutlet UIButton *bcardButton;

@end

@implementation UploadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"经纪人认证"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"nav_back.png"] Target:self Selector:@selector(back)];
    
    self.idcardButton.exclusiveTouch = YES;
    self.bcardButton.exclusiveTouch = YES;
    
    fileDic = [NSMutableDictionary dictionary];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark 上传相关
- (IBAction)choose:(UIButton *)sender {
    
    tempTag = sender.tag;
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传", @"手机相册上传", nil];
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (actionSheet.cancelButtonIndex != buttonIndex) {
        // 拍照上传
        if (0 == buttonIndex) {
            [self camera];
        }
        // 手机相册上传
        else if (1 == buttonIndex) {
            [self photoLibrary];
        }
    }
}

#pragma mark 照相机
- (void)camera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

#pragma mark 照片库
- (void)photoLibrary {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqual:(NSString *)kUTTypeImage]) {
        UIImage *img = info[UIImagePickerControllerOriginalImage];
        CGSize size = img.size;
        CGFloat ratio = 1;
        if (size.width > 640) {
            ratio = 640 / size.width;
        }
        int ratwid = ratio * size.width;
        int rathig = ratio * size.height;
        if (ratwid < 1) {
            ratwid = 1;
        }
        if (rathig < 1) {
            rathig = 1;
        }
        
        CGRect rect = CGRectMake(0.0, 0.0, ratwid, rathig);
        UIGraphicsBeginImageContext(rect.size);
        [img drawInRect:rect];
        img = UIGraphicsGetImageFromCurrentImageContext();
        
        NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
        img = [UIImage imageWithData:imgData];
        NSString *filePath = [self saveImageToHome:img];
        
        // 身份证
        if (tempTag == 991125) {
            [fileDic setObject:filePath forKey:@"idcardImg1"];
            [self.idcardButton setImage:img forState:UIControlStateNormal];
        }
        // 名片
        else if (tempTag == 991126) {
            [fileDic setObject:filePath forKey:@"bcardImg"];
            [self.bcardButton setImage:img forState:UIControlStateNormal];
        }
    } else {
        showAlertMessage(@"请选择照片");
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (NSString *)saveImageToHome:(UIImage *)image {
    NSString *imgName = _S(@"img_%.0f.jpg",[[NSDate date] timeIntervalSince1970]);
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:HomeImagePath]) {
        [manager createDirectoryAtPath:HomeImagePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString * path = _S(@"%@/%@",HomeImagePath,imgName);
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];
    return path;
}

- (IBAction)upload:(id)sender {
    if (fileDic == nil || fileDic.count == 0) {
        showAlertMessage(@"请上传身份证");
        return;
    }
    if ([fileDic objectForKey:@"idcardImg1"] == nil) {
        showAlertMessage(@"请上传身份证");
        return;
    }
    if ([fileDic objectForKey:@"bcardImg"] == nil) {
        showAlertMessage(@"请上传名片");
        return;
    }
    
    [[BaseEngine sharedEngine] setPostFileDict:fileDic];
    
    __weak UploadViewController *weak_self = self;
    MKNetworkOperation *op = [[BaseEngine sharedEngine] RunRequest:nil path:KFC_UPLOAD completionHandler:^(NSDictionary *responseDict) {
        showAlertMessage(@"上传成功");
        [weak_self back];
    } errorHandler:^(NSError *error) {
        showCustomAlertMessage(@"网路错误");
        [fileDic removeAllObjects];
    } finishHandler:^(id resString) {
    }];
    
    [self.opHandlers addObject:op];
}

#pragma mark -
#pragma mark
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
